#include "XModFile.h"


XModFile::XModFile(){
	str_file = "";
	f_handle = NULL;
}

XModFile::~XModFile(){
	if (IsOpen())
		Close();
}

bool XModFile::Exist(string file){
	return _access(file.c_str(), 0) != -1;
}

bool XModFile::OpenFile(string file,FileMode mode){
	if (!Exist(file))
		return false;
	str_file = file;
	switch (mode)
	{
	default:
	case FM_READ:
		f_handle = fopen(file.c_str(), "r");
		break;

	case FM_WRITE:
		f_handle = fopen(file.c_str(), "w");
		break;

	case FM_APPEND:
		f_handle = fopen(file.c_str(), "a");
		break;

	case FM_READ_WRITE:
		f_handle = fopen(file.c_str(), "w+");
		break;

	case FM_READ_WRITE_APPEND:
		f_handle = fopen(file.c_str(), "a+");
		break;

	case FM_READ_BINARY:
		f_handle = fopen(file.c_str(), "rb");
		break;

	case FM_WRITE_BINARY:
		f_handle = fopen(file.c_str(), "wb");
		break;

	case FM_APPEND_BINARY:
		f_handle = fopen(file.c_str(), "ab");
		break;

	case FM_READ_WRITE_BINARY:
		f_handle = fopen(file.c_str(), "r+b");
		break;

	case FM_READ_WRITE_APPEND_BINARY:
		f_handle = fopen(file.c_str(), "a+b");
		break;
	}
	return true;
}

void XModFile::Close(){
	if (f_handle != NULL)
		fclose(f_handle);
	f_handle = NULL;
}

string XModFile::GetFileName(){
	return str_file;
}

string XModFile::GetExternName(){
	int i_len = str_file.length();
	while (i_len > 0 && str_file[i_len] != '.'){
		i_len--;
	}
	if (i_len < 1 || str_file[i_len] != '.')
		return "";
	return string(&str_file[i_len]);
}

bool XModFile::IsOpen(){
	return f_handle != NULL;
}

FILE* XModFile::GetHandle(){
	return f_handle;
}

int XModFile::GetSize(){
	int i_cur = ftell(f_handle);
	fseek(f_handle, 0, SEEK_END);
	int i_size = ftell(f_handle);
	fseek(f_handle, i_cur, SEEK_SET);
	return i_size;
}

string XModFile::GetRootPath(){
	char a[1024];
	GetCurrentDirectory(1024, a);
	string s(a);
	return s;
}